<template>
  <el-header :style="'margin-bottom:'+ headerBottom +'px'">
    <router-link to="/">
      <h1 class="logo" style="color: #30B08F;">嘉应书轩</h1>
    </router-link>
    <div class="bg-purple-light">
      <el-menu :default-active="activeIndex" router mode="horizontal" style="border: none;"
               background-color="#545c64" text-color="#fff" active-text-color="#FD0000">
        <el-menu-item :index="item.path" v-for="item in menulist" :key="item.id"
                      style="color: black;text-align: center">
          <el-row>
            <el-col>
              <i :class="item.icon" style="color: black;"></i>
            </el-col>
            <el-col style="position: relative;top: -30px;">
              {{ item.authName }}
            </el-col>
          </el-row>
        </el-menu-item>
      </el-menu>
      <div v-if="noticeList.length > 0" style="position: absolute; left: 400px; top: 20px; display: flex; align-items: center;">
        <el-tag 
          size="small" 
          :type="noticeList[0].noticeType === '2' ? 'success' : ''" 
          :class="{'notice-tag-custom-info': noticeList[0].noticeType === '1'}"
          style="margin-right: 10px;"
        >
          {{ noticeList[0].noticeType === '2' ? '公告' : '通知' }}
        </el-tag>
        <el-tooltip class="item" effect="dark" :content="noticeList[0].noticeTitle" placement="bottom">
          <span :style="{ color: noticeList[0].noticeType === '2' ? 'rgb(48, 176, 143)' : '#409EFF', fontSize: '14px', cursor: 'pointer' }">{{ noticeList[0].noticeTitle | ellipsisNoticeTitle }}</span>
        </el-tooltip>
      </div>
      <div style="position: absolute;right: 160px;top: 20px;text-align: center;">

        <el-popover
            placement="bottom"
            width="400"
            v-if="this.islogin"
            trigger="hover">
          <el-tabs :stretch="true" v-model="tabName">
            <el-tab-pane label="评论回复" name="comment">
              <div v-if="this.unreadCommentList.length != 0">
                <el-card shadow="hover" v-for="(item,index) in unreadCommentList" :key="index" style="margin-top: 3px;"
                         body-style="padding:6px 2px 6px 2px">
                  <div @click="openComment(item.comment)">
                    <el-row>
                      <el-col :span="3">
                        <el-avatar
                            :src="baseUrl+item.comment.sysUser.avatar"
                            shape="square" style="vertical-align: middle;">
                        </el-avatar>
                      </el-col>
                      <el-col :span="21">
                        <span style="font-size: 16px;">{{ item.comment.sysUser.nickName }}</span>
                        <p style="line-height: 0;font-size: 14px;color: #606266">
                          {{ item.comment.commentText| ellipsis }}
                        </p>
                      </el-col>
                    </el-row>
                  </div>
                </el-card>
              </div>
              <p v-else style="text-align: center;margin: 0">
                暂无评论~
              </p>
            </el-tab-pane>
          </el-tabs>
          <el-badge :value="unreadCommentList.length"
                    :hidden="(this.unreadCommentList.length) == 0"
                    style="margin-right: 20px" slot="reference">
            <el-button type="text" style="color: rgb(48 176 143);">
              <i class="el-icon-chat-line-round"></i>
              <p style="font-size: 14px;margin-top: 3px;">消息</p>
            </el-button>
          </el-badge>
        </el-popover>

        <el-dropdown placement="bottom">
          <span class="el-dropdown-link">
              <el-badge is-dot hidden>
                <el-button type="text" style="color: rgb(48 176 143)">
                  <i class="el-icon-time"></i>
                  <p style="font-size: 14px;margin-top: 2px;">最近阅读</p>
                </el-button>
             </el-badge>
          </span>
          <el-dropdown-menu slot="dropdown" class="dropdownMenu">
            <el-dropdown-item disabled>
              <p style="text-align: center;margin: 0">
                {{ this.islogin ? "只保存24小时内的浏览历史" : "登录查看吧~" }}
              </p>
            </el-dropdown-item>
            <el-dropdown-item v-for="(o, index) in booksHistoryList" @click.native="jump(2,o)" :key="index">
              <el-card shadow="hover">
                <el-row>
                  <el-col :span="12">
                    <el-image
                        style="width: 60px;height:80px;border-radius: 4px"
                        fit="cover"
                        :src="baseUrl+o.bookCover"></el-image>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <h3>{{ o.bookName }}</h3>
                    </div>
                  </el-col>
                </el-row>
              </el-card>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div v-if="islogin" class="bg-purple" style="position: relative;top: 10px">
      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <el-avatar class="user-avatar" :src="avatar" @error="errorHandler">
            <i class="el-icon-s-custom"/>
          </el-avatar>
          <p class="avatar-Name">{{ nickName | ellipsisName }}</p>
        </div>
        <el-dropdown-menu slot="dropdown">
          <router-link target="_blank" to="/index">
            <el-dropdown-item>创作中心</el-dropdown-item>
          </router-link>
          <router-link target="_blank" to="/cms/main/cmsMine">
            <el-dropdown-item>个人中心</el-dropdown-item>
          </router-link>
          <el-dropdown-item divided @click.native="logout">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div v-else class="bg-purple">
      <div class="avatar-wrapper">
        <el-row>
          <el-col style="position: relative;top: 20px">
            <i class="el-icon-user"/>
          </el-col>
          <el-col style="position: relative; right: 46px;top: 15px;">
            <p class="avatar-Name" @click="tologin">登录|注册</p>
          </el-col>
        </el-row>
      </div>
    </div>

    <el-dialog
        title="回复评论"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
      <span style="font-size: 18px;line-height: 38px">{{ this.comment.sysUser.nickName }} 评论你：<span
          style="color: #3A71A8">{{ this.comment.commentText }}</span></span>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="发表评论">
          <el-input type="textarea" v-model="form.commentText"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="float: right" type="primary" @click="onSubmit">发表</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </el-header>
</template>

<script>
import {
  mapGetters
} from 'vuex'
import {
  getToken
} from '@/utils/auth'
import 'element-ui/lib/theme-chalk/display.css'
import {listHistory} from "../../api/bookM/books";
import {getInfo} from "../../api/login";
import {addComment, readComment, unreadComment} from "../../api/comment/comment";
import {computerIp} from "../../config.js"
import { listPublicNotice } from "@/api/system/notice";

let socketMain;
export default {
  name: 'cmsNavBar',
  filters: {
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 26) {
        return value.slice(0, 26) + '...'
      }
      return value
    },
    ellipsisName(value) {
      if (!value) return ''
      if (value.length > 10) {
        return value.slice(0, 10) + '...'
      }
      return value
    },
    ellipsisNoticeTitle(value) {
      if (!value) return ''
      if (value.length > 30) {
        return value.slice(0, 30) + '...'
      }
      return value
    }
  },
  data() {
    return {
      tabName: 'comment',
      activeIndex: 'this.$router.path',
      islogin: false,
      menuHiddenVisiable: false,
      centerDialogVisible: false,
      searchInput: true,
      headerBottom: 0,
      queryInfo: {
        query: '',
        timer: null
      },
      form: {
        commentText: ''
      },
      searchList: [],
      searching: false,
      menulist: [{
        id: 0,
        authName: '首页',
        path: '/cms/main/cmsIndex',
        icon: 'el-icon-monitor',
      }, {
        id: 1,
        authName: '社区广场',
        path: '/cms/main/cmsBBS',
        icon: 'el-icon-guide',
      },],
      baseUrl: process.env.VUE_APP_BASE_API,
      booksHistoryList: [],
      unreadCommentList: [],
      commentList: [],
      userId: "",
      comment: {
        sysUser: {}
      },
      noticeList: [],
      loading: false
    };
  },
  computed: {
    ...mapGetters([
      'avatar',
      'nickName'
    ]),
  },
  components: {},
  created() {
    this.login();
    this.getHistory();
    this.getNoticeList();
  },
  methods: {
    onSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addComment(this.form).then(res => {
            this.centerDialogVisible = false;
            this.form.commentText = ''
            this.$message.success(res.msg)
            this.getUnreadComment()
          })
        }
      })
    },
    // 获取未读评论
    getUnreadComment() {
      unreadComment().then(res => {
        this.unreadCommentList = res.rows
      })
    },
    // 打开评论框
    openComment(comment) {
      this.centerDialogVisible = true
      this.comment = comment
    },
    //获取历史记录
    getHistory() {
      listHistory().then(res => {
        this.booksHistoryList = res.rows
      })
    },
    //登录
    login() {
      if (getToken() == undefined) {
        this.islogin = false;
      } else {
        this.islogin = true;
        this.userId = this.$store.getters.userId
      }
    },
    errorHandler() {
      return true
    },
    async logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          location.href = '/'
        })
      }).catch(() => {
      });
    },
    tologin() {
      this.$router.push('/login')
    },
    jump(type, parm) {
      switch (type) {
        //书籍
        case 2:
          let routeUrl = this.$router.resolve({
            path: '/cms/main/cmsDetail',
            query: {
              pptUrl: parm.bookId
            }
          })
          window.open(routeUrl.href, '_blank')
          break
      }
    },
    getNoticeList() {
      this.loading = true;
      listPublicNotice().then(response => {
        if (response && response.rows) {
          this.noticeList = response.rows.filter(notice => notice && notice.noticeTitle);
        } else {
          this.noticeList = [];
          console.warn('获取通知数据格式不正确');
        }
      }).catch(error => {
        this.noticeList = [];
        console.error('获取通知失败:', error);
      }).finally(() => {
        this.loading = false;
      });
    },
    handleCommand(command) {
      // 处理通知点击事件
    }
  },
  mounted() {
    //初始化websocket
    if (getToken() != undefined) {
      //连接websocket
      // this.websock = new WebSocket("ws://localhost:8080/websocket/"+this.userId);
      this.websock = new WebSocket("ws://" + computerIp + ":8080/websocket/" + this.userId);
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    }
  },
  destroyed() {
    if (getToken() != undefined) {
      this.websock.close()
    }
  },
}
</script>

<style scoped>
.el-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: .2s;
}

.el-header:hover {
  opacity: 1 !important;
}

.el-menu {
  flex-shrink: 0;
  background-color: rgba(0, 0, 0, 0) !important;
}

.el-menu /deep/ .el-menu-item {
  height: 70px;
  background-color: rgba(0, 0, 0, 0) !important;
}


.el-menu /deep/ .el-menu-item i {
  color: rgba(255, 255, 255);
}

.el-menu /deep/ .el-menu-item:hover i {
  color: white;
}

.el-menu /deep/ .el-menu-item:hover {
  background-color: rgba(48, 176, 143, 0.5) !important;
}


.bg-purple-light {
  float: right;
}

.bg-purple {
  float: right;
}

.user-avatar {
  float: left;
  cursor: pointer;
  border: dashed rgba(255, 255, 127, 0.5);
}

.avatar-container {
  margin-right: 30px;
}

.avatar-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-Name {
  margin-left: 10px;
  cursor: pointer;
  float: right;
  font-size: 14px;
  color: #000000;
}

.logo {
  float: left;
  margin-left: 50px;
  margin-top: 46px;
  color: #000000;
  font-size: 42px;
  font-weight: bold;
}

.logo:hover {
  cursor: pointer;
}

.el-dropdown-menu.dropdownMenu {
  overflow: scroll;
  max-height: 300px;
  overflow-x: hidden;
}

.notice-tag-custom-info {
  background-color: #ECF5FF !important; 
  border-color: #A0CFFF !important;
  color: #409EFF !important; 
}
</style>
